package org.browntooth.app.bluetooth;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

public class BluetoothDeviceConnection {
	private final BluetoothDevice device;
	private final UUID serviceUuid;
	private final BluetoothSocket socket;
	private boolean isOpen;

	public BluetoothDeviceConnection(BluetoothDevice device, UUID serviceUuid, BluetoothSocket socket) {
		this.device = device;
		this.serviceUuid = serviceUuid;
		this.socket = socket;

		isOpen = true;
	}

	public String getDeviceAddress() {
		if (device != null) {
			return device.getAddress();
		}
		return null;
	}

	public String getDeviceName() {
		if (device != null) {
			return device.getName();
		}
		return null;
	}

	public UUID getServiceUuid() {
		return serviceUuid;
	}

	public InputStream getInputStream() throws IOException {
		validateOpen();

		return socket.getInputStream();
	}

	public OutputStream getOutputStream() throws IOException {
		validateOpen();

		return socket.getOutputStream();
	}

	public void close() throws IOException {
		if (isOpen) {
			socket.close();
			isOpen = false;
		}
	}

	private void validateOpen() {
		if (!isOpen) {
			throw new IllegalStateException("The socket was closed!");
		}
	}
}
